<template>
  <div v-loading="loading" class="app-container uni-scroll" style="height: calc(100vh - 100px);">
    <div>
      <el-row :gutter="10">
        <el-col v-for="(item,index) in myDeviceCoreList" :key="index" :span="6">
          <el-input :value="item">
            <template slot="append">
              <el-button type="danger" @click="removeDeviceCore(item)">{{ $t('delete') }}</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-input v-model="deviceCore">
            <template slot="append">
              <el-button type="primary" @click="addDeviceCore">{{ $t('add') }}</el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>
    <div v-if="!loading" style="margin-top: 10px">
      <el-button-group>
        <el-button
          round
          type="primary"
          @click="searchWeek"
        >{{ $t('one')+$t('week') }}
        </el-button>
        <el-button
          type="primary"
          @click="searchMonth"
        >{{ $t('one')+$t('month') }}
        </el-button>
        <el-button
          type="primary"
          @click="search3month"
        >{{ $t('three')+$t('month') }}
        </el-button>
      </el-button-group>
      <el-date-picker
        v-model="startDate"
        type="datetime"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-date-picker
        v-model="endDate"
        type="datetime"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="init"
        >{{ $t('search') }}
        </el-button>
      </el-button-group>
    </div>
    <div v-for="(sensor,sensorIndex) in sensorList" :key="sensorIndex">
      <div
        class="primary-color"
        style="line-height: 40px;font-size:15px;margin-left: 13px"
      >
        {{ sensor.name }}
        <span style="color: #34bfa3;margin-left: 13px">[{{ formatSensorType(sensor.type) }}{{ $t('port') }}:{{ sensor.port }}]</span>
      </div>
      <div v-for="(item,index) in sensor.canvasList" :key="index" class="box-card">
        <multi-line-chart
          style="height: 450px;margin-bottom: 13px;margin-left: 13px;width: 98%"
          :chart-data="item"
        />
      </div>
    </div>
    <div style="margin-top: 13px;margin-left: 25px">
      <el-switch
        v-model="filterRepeat"
        style=";margin-right: 5px"
        active-value="1"
        inactive-value="0"
        :active-text="$t('filter')+$t('repeat')"
        @change="filterRepeatChange"
      />
      <el-switch
        v-model="enableEval"
        active-value="1"
        inactive-value="0"
        :active-text="$t('enable')+$t('script')"
        @change="enableEvalChange"
      />
    </div>
  </div>
</template>

<script>
import MultiLineChart from '@/components/Chart/MultiLineChart'
import {
  failureNotice,
  formatDate,
  formatSensorType
} from '@/util/common'
import {
  getFilterRepeat,
  setFilterRepeat,
  getEnableEval,
  setEnableEval
} from '@/util/storage'
import { listWithExplain } from '@/api/iot/iotDeviceSensorDataApi'
import { batchSensorWith } from '@/api/iot/iotDeviceSensorApi'
import resize from '@/components/Mixins/resize'
import { detailsDevice } from '@/api/iot/iotDeviceApi'
export default {
  name: 'DeviceSensorAnalysis',
  components: {
    MultiLineChart
  },
  mixins: [resize],
  props: {
    deviceCoreList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      deviceIdToDeviceCore: {},
      myDeviceCoreList: [],
      sensorList: [],
      deviceCore: null,
      startDate: '',
      endDate: '',
      pickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      loading: false,
      filterRepeat: getFilterRepeat(),
      enableEval: getEnableEval()
    }
  },
  created() {
    const timestamp = new Date().getTime()
    this.startDate = timestamp - 3 * 24 * 60 * 60 * 1000
    this.endDate = timestamp
    this.myDeviceCoreList = this.deviceCoreList
    this.init()
  },
  methods: {
    filterRepeatChange() {
      setFilterRepeat(this.filterRepeat)
      this.listSensor()
    },
    enableEvalChange() {
      setEnableEval(this.enableEval)
      this.listSensor()
    },
    removeDeviceCore(deviceCore) {
      for (const i in this.myDeviceCoreList) {
        if (this.myDeviceCoreList[i] === deviceCore) {
          this.myDeviceCoreList.splice(i, 1)
          break
        }
      }
      this.init()
    },
    addDeviceCore() {
      this.detailsDevice()
    },
    detailsDevice() {
      detailsDevice({
        'deviceCore': this.deviceCore
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.myDeviceCoreList.push(this.deviceCore)
          this.deviceCore = ''
          this.init()
        }
      })
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    init() {
      this.batchSensorWith()
    },
    batchSensorWith() {
      this.loading = true
      this.sensorList = []
      batchSensorWith({
        deviceCoreList: this.myDeviceCoreList,
        withExplain: true,
        hidden: false
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const dataRest = {}
          data.forEach(device => {
            let sensor
            for (sensor of device.sensorList) {
              this.deviceIdToDeviceCore[sensor.deviceId] = device.deviceCore
              let sensorExist = false
              let item
              for (item of this.sensorList) {
                if (item.port === sensor.port) {
                  sensorExist = true
                  break
                }
              }
              if (!sensorExist) {
                const explainList = []
                for (let i = 0, j = sensor.explainList.length; i < j; i++) {
                  const explain = sensor.explainList[i]
                  if (explain.type !== 'line') {
                    continue
                  }
                  explain.title = explain.name + '(' + explain.unit + ')'
                  explain.dataList = []
                  explain.dateList = []
                  explainList.push(explain)
                }
                this.sensorList.push({
                  type: sensor.type,
                  name: sensor.sensorName,
                  port: sensor.port,
                  canvasList: explainList
                })
              }
              if (!dataRest[sensor.port]) {
                dataRest[sensor.port] = []
              }
              dataRest[sensor.port].push(
                listWithExplain({
                  sensorId: sensor.sensorId,
                  startTime: Math.round(this.startDate / 1000),
                  endTime: Math.round(this.endDate / 1000),
                  enableEval: this.enableEval === '1',
                  filterRepeat: this.filterRepeat === '1'
                })
              )
            }
          })

          const that = this
          for (const port in dataRest) {
            Promise.all(dataRest[port]).then(resList => {
              let sensor = null
              for (const item of that.sensorList) {
                if (item.port === port) {
                  sensor = item
                  break
                }
              }
              const deviceExplainMap = {}
              resList.forEach(res => {
                const { code, data } = res
                if (code === '200') {
                  const dataList = data.dataList
                  /**
                     * 装换时间
                     */
                  for (let i = 0, j = dataList.length; i < j; i++) {
                    dataList[i].createdTime = formatDate(that, dataList[i].createdTime)
                  }

                  const explainMap = {}
                  for (const canvasItem of sensor.canvasList) {
                    if (canvasItem.type !== 'line') {
                      continue
                    }
                    for (let i = 0, j = dataList.length; i < j; i++) {
                      const dataBean = dataList[i].val
                      if (dataBean[canvasItem.keyName]) {
                        if (!explainMap[canvasItem.keyName]) {
                          explainMap[canvasItem.keyName] = []
                        }

                        explainMap[canvasItem.keyName].push({
                          val: dataBean[canvasItem.keyName],
                          time: dataList[i].createdTime
                        })
                      }
                    }
                  }

                  deviceExplainMap[that.deviceIdToDeviceCore[data.explainList[0].deviceId]] = explainMap
                }
              })
              that.makeCanvasList(sensor, deviceExplainMap)
            })
          }
        }
      })
    },
    makeCanvasList(sensor, deviceExplainMap) {
      const canvasList = []
      let deviceCore
      for (deviceCore in deviceExplainMap) {
        break
      }
      for (const keyName in deviceExplainMap[deviceCore]) {
        canvasList.push(this.makeCanvasItem(keyName, deviceExplainMap))
      }
      sensor.canvasList = canvasList
      this.loading = false
    },
    makeCanvasItem(keyName, deviceExplainMap) {
      const canvasItem = {
        dateList: [],
        dataList: []
      }
      let i = 0
      for (const deviceCore in deviceExplainMap) {
        const dataList = {
          name: deviceCore,
          dataList: []
        }
        const item = deviceExplainMap[deviceCore]
        const dataAndDateList = item[keyName]
        if (dataAndDateList) {
          dataAndDateList.forEach(dataAndDate => {
            if (i === 0) {
              canvasItem.dateList.push(dataAndDate.time)
            }
            dataList.dataList.push(dataAndDate.val)
          })
          i = 1
        }
        canvasItem.dataList.push(dataList)
      }
      return canvasItem
    },
    search3month() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 3 * 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.init()
    },
    searchMonth() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.init()
    },
    searchWeek() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.init()
    }
  }
}
</script>
<style scoped lang="scss">
  @import '@/styles/element-variables.scss';

  .primary-color {
    color: $--color-primary;
  }

</style>
